﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;

namespace Demo.Helpers
{
    public static class IEnumerableExtensions
    {
        public static IEnumerable<ExpandoObject> ShapeData<TSource>(this IEnumerable<TSource> source, string fields)
        {
            if (source == null) throw new ArgumentNullException(nameof(source));

            var expandoObjectList = new List<ExpandoObject>(source.Count());

            var propertyInfoList = new List<PropertyInfo>();

            var sourceProperties =
                typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);

            if (!string.IsNullOrWhiteSpace(fields))
            {
                var fieldsArr = fields.Split(',', StringSplitOptions.RemoveEmptyEntries);

                sourceProperties = sourceProperties.Where(x => fieldsArr.Contains(x.Name)).ToArray();
            }

            propertyInfoList.AddRange(sourceProperties);

            foreach (var obj in source)
            {
                var expandoObj = new ExpandoObject();

                foreach (var propertyInfo in propertyInfoList)
                {
                    ((IDictionary<string, object>) expandoObj).Add(propertyInfo.Name, propertyInfo.GetValue(obj));
                }

                expandoObjectList.Add(expandoObj);
            }

            return expandoObjectList;
        }
    }
}